package itsm.isperp.module.service.slm;

import itsm.isperp.framework.data.commons.repository.BaseRepository;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.module.entity.slm.SlmAlarmObject;
import itsm.isperp.module.repository.slm.SlmAlarmObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.support.DatabaseType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class SlmAlarmObjectService extends BaseService<SlmAlarmObject> {

	@Autowired
	protected SlmAlarmObjectMapper slmAlarmObjectMapper;
	@Autowired
	protected JdbcTemplate jdbcTemplate;

	@Override
	public BaseRepository<SlmAlarmObject> getRepository() {
		return this.slmAlarmObjectMapper;
	}

	public void deleteBySettingId(String settingId) {

		slmAlarmObjectMapper.deleteBySettingId(settingId);

	}

	public void deleteByServiceTargetId(String serviceTargetId) {

		if (DialectFactory.getDatabaseType() == DatabaseType.MYSQL) {

			slmAlarmObjectMapper.deleteByServiceTargetId(serviceTargetId);

		} else {

			String sql = "DELETE FROM slm_alarm_object 	WHERE id IN (SELECT a.id  FROM slm_alarm_object a "
					+ "LEFT JOIN slm_alarm_setting b ON a.relation_id=b.id WHERE b.service_target_id='"
					+ serviceTargetId + "')";
			jdbcTemplate.execute(sql);

		}
	}

	public void deleteByAgreementId(String agreementId) {

		if (DialectFactory.getDatabaseType() == DatabaseType.MYSQL) {

			slmAlarmObjectMapper.deleteByServiceTargetId(agreementId);
		} else {

			String sql = "DELETE  slm_alarm_object 	WHERE id IN  (SELECT a.id  FROM slm_alarm_object a "
					+ "LEFT JOIN slm_alarm_setting b ON a.relation_id=b.id "
					+ "LEFT JOIN slm_service_target c ON b.service_target_id=c.id WHERE c.agreement_id='"
					+ agreementId + "')";

			jdbcTemplate.execute(sql);

		}

	}

	public void deleteByProjectId(String projectId) {

		if (DialectFactory.getDatabaseType() == DatabaseType.MYSQL) {
			slmAlarmObjectMapper.deleteByProjectId(projectId);
		} else {

			String sql = "DELETE  slm_alarm_object 	WHERE id IN  (SELECT a.id  FROM slm_alarm_object a "
					+ "LEFT JOIN slm_alarm_setting b ON a.relation_id=b.id "
					+ "LEFT JOIN slm_service_target c ON b.service_target_id=c.id "
					+ "LEFT JOIN slm_service_agreement d ON c.agreement_id=d.id WHERE d.project_id='"
					+ projectId + "')";

			jdbcTemplate.execute(sql);

		}

	}

}
